using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using hao_Dto;
using hao_Common.Response.Extensions;
using hao_Common.Logging.Helpers;
using Order.Service;
using System.Security.Claims;
using hao_Model.Enums;
using hao_Common.Http.Interfaces;
using hao_Common.Consul.Services;
using System.Text.Json;

namespace hao_Order.Api.Controllers
{
    [ApiController]
    [Route("api/order")]
    [Authorize]
    public class OrdersController : ControllerBase
    {
        private readonly IOrderService _orderService;
        private readonly IHttpHelper _httpHelper;
        private readonly IServiceDiscovery _serviceDiscovery;
        private readonly ILogger<OrdersController> _logger;

        public OrdersController(
            IOrderService orderService, 
            IHttpHelper httpHelper,
            IServiceDiscovery serviceDiscovery,
            ILogger<OrdersController> logger)
        {
            _orderService = orderService;
            _httpHelper = httpHelper;
            _serviceDiscovery = serviceDiscovery;
            _logger = logger;
        }

        /// <summary>
        /// 创建订单
        /// </summary>
        [HttpPost("create")]
        [Authorize]
        public async Task<IActionResult> CreateOrder([FromBody] CreateOrderDto dto)
        {
            var userId = GetCurrentUserId();
            var ipAddress = HttpContext.Connection.RemoteIpAddress?.ToString();
            
            _logger.LogUserAction(userId.ToString(), "创建订单", new { ProductId = dto.ProductId, FinalPrice = dto.FinalPrice }, ipAddress);
            
            try
            {
                var orderId = await _orderService.CreateOrderAsync(dto, userId);
                
                _logger.LogBusinessOperation("订单创建成功", new { OrderId = orderId, UserId = userId, ProductId = dto.ProductId });
                
                return this.SuccessResult(new { OrderId = orderId }, "订单创建成功");
            }
            catch (UnauthorizedAccessException ex)
            {
                _logger.LogWarning(ex, "用户未授权访问");
                return this.UnauthorizedResult(ex.Message);
            }
            catch (ArgumentException ex)
            {
                return this.ValidationFailResult(ex.Message);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建订单失败");
                return this.ServerErrorResult("创建订单失败");
            }
        }

        /// <summary>
        /// 获取订单详情
        /// </summary>
        [HttpGet("{id}")]
        public async Task<IActionResult> GetOrder(Guid id)
        {
            try
            {
                var userId = GetCurrentUserId();
                if (!await _orderService.ValidateOrderOwnershipAsync(id, userId))
                {
                    return this.ForbiddenResult("无权访问此订单");
                }

                var order = await _orderService.GetOrderByIdAsync(id);
                if (order == null)
                {
                    return this.NotFoundResult("订单不存在");
                }

                return this.SuccessResult(order);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取订单详情失败!");
                return this.ServerErrorResult("获取订单详情失败");
            }
        }

        /// <summary>
        /// 根据订单号获取订单
        /// </summary>
        [HttpGet("number/{orderNumber}")]
        public async Task<IActionResult> GetOrderByNumber(string orderNumber)
        {
            try
            {
                var order = await _orderService.GetOrderByNumberAsync(orderNumber);
                if (order == null)
                {
                    return this.NotFoundResult("订单不存在");
                }

                var userId = GetCurrentUserId();
                if (!await _orderService.ValidateOrderOwnershipAsync(order.Id, userId))
                {
                    return this.ForbiddenResult("无权访问此订单");
                }

                return this.SuccessResult(order);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取订单失败");
                return this.ServerErrorResult("获取订单失败");
            }
        }

        /// <summary>
        /// 获取订单列表
        /// </summary>
        [HttpPost("list")]
        public async Task<IActionResult> GetOrders([FromBody] OrderSearchDto searchDto)
        {
            try
            {
                var userId = GetCurrentUserId();
                // 限制用户只能查看自己相关的订单
                if (!searchDto.BuyerId.HasValue && !searchDto.SellerId.HasValue)
                {
                    searchDto.BuyerId = userId;
                }
                else if (searchDto.BuyerId.HasValue && searchDto.BuyerId.Value != userId &&
                         searchDto.SellerId.HasValue && searchDto.SellerId.Value != userId)
                {
                    return this.ForbiddenResult("只能查看自己相关的订单");
                }

                var (orders, total) = await _orderService.GetOrdersAsync(searchDto);
                return this.SuccessResult(new { Orders = orders, Total = total });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取订单列表失败");
                return this.ServerErrorResult("获取订单列表失败");
            }
        }

        /// <summary>
        /// 获取买家订单列表
        /// </summary>
        [HttpGet("buyer")]
        public async Task<IActionResult> GetBuyerOrders([FromQuery] OrderStatus? status = null)
        {
            try
            {
                var userId = GetCurrentUserId();
                var orders = await _orderService.GetBuyerOrdersAsync(userId, status);
                return this.SuccessResult(orders);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取买家订单失败");
                return this.ServerErrorResult("获取买家订单失败");
            }
        }

        /// <summary>
        /// 获取卖家订单列表
        /// </summary>
        [HttpGet("seller")]
        public async Task<IActionResult> GetSellerOrders([FromQuery] OrderStatus? status = null)
        {
            try
            {
                var userId = GetCurrentUserId();
                var orders = await _orderService.GetSellerOrdersAsync(userId, status);
                return this.SuccessResult(orders);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取卖家订单失败");
                return this.ServerErrorResult("获取卖家订单失败");
            }
        }

        /// <summary>
        /// 卖家确认订单
        /// </summary>
        [HttpPut("{id}/seller-confirm")]
        public async Task<IActionResult> SellerConfirmOrder(Guid id, [FromBody] SellerConfirmDto dto)
        {
            try
            {
                var userId = GetCurrentUserId();
                if (!await _orderService.ValidateSellerOwnershipAsync(id, userId))
                {
                    return this.ForbiddenResult("无权操作此订单");
                }

                var result = await _orderService.SellerConfirmOrderAsync(id, userId, dto?.SellerMessage);
                if (result)
                {
                    return this.SuccessResult("订单确认成功");
                }
                else
                {
                    return this.FailResult("订单确认失败");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "卖家确认订单失败");
                return this.ServerErrorResult("卖家确认订单失败");
            }
        }

        /// <summary>
        /// 确认收货
        /// </summary>
        [HttpPut("{id}/confirm")]
        public async Task<IActionResult> ConfirmReceipt(Guid id)
        {
            try
            {
                var userId = GetCurrentUserId();
                if (!await _orderService.CanConfirmOrderAsync(id))
                {
                    return this.ValidationFailResult("订单状态不允许确认收货");
                }

                var result = await _orderService.ConfirmReceiptAsync(id, userId);
                if (result)
                {
                    return this.SuccessResult("确认收货成功");
                }
                else
                {
                    return this.FailResult("确认收货失败");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "确认收货失败");
                return this.ServerErrorResult("确认收货失败");
            }
        }

        /// <summary>
        /// 取消订单
        /// </summary>
        [HttpPut("{id}/cancel")]
        public async Task<IActionResult> CancelOrder(Guid id, [FromBody] CancelOrderDto dto)
        {
            try
            {
                var userId = GetCurrentUserId();
                if (!await _orderService.ValidateOrderOwnershipAsync(id, userId))
                {
                    return this.ForbiddenResult("无权操作此订单");
                }

                if (!await _orderService.CanCancelOrderAsync(id))
                {
                    return this.ValidationFailResult("订单状态不允许取消");
                }

                var result = await _orderService.CancelOrderAsync(id, dto.Reason, userId);
                if (result)
                {
                    return this.SuccessResult("取消订单成功");
                }
                else
                {
                    return this.FailResult("取消订单失败");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "取消订单失败");
                return this.ServerErrorResult("取消订单失败");
            }
        }

        /// <summary>
        /// 获取物流信息
        /// </summary>
        [HttpGet("{id}/tracking")]
        public async Task<IActionResult> GetTrackingInfo(Guid id)
        {
            try
            {
                var userId = GetCurrentUserId();
                if (!await _orderService.ValidateOrderOwnershipAsync(id, userId))
                {
                    return this.ForbiddenResult("无权访问此订单");
                }

                var order = await _orderService.GetOrderByIdAsync(id);
                if (order == null || string.IsNullOrEmpty(order.TrackingNumber))
                {
                    return this.NotFoundResult("暂无物流信息");
                }

                var trackingInfo = await _orderService.GetTrackingInfoAsync(order.TrackingNumber);
                return this.SuccessResult(trackingInfo);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取物流信息失败");
                return this.ServerErrorResult("获取物流信息失败");
            }
        }

        /// <summary>
        /// 获取订单统计
        /// </summary>
        [HttpGet("statistics")]
        public async Task<IActionResult> GetStatistics()
        {
            try
            {
                var userId = GetCurrentUserId();
                var statistics = await _orderService.GetOrderStatisticsAsync(userId);
                return this.SuccessResult(statistics);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取订单统计失败");
                return this.ServerErrorResult("获取订单统计失败");
            }
        }

        #region 服务间通信测试接口

        /// <summary>
        /// 测试调用用户服务 - 获取用户信息
        /// </summary>
        [HttpGet("test/user/{userId}")]
        [AllowAnonymous]
        public async Task<IActionResult> TestGetUser(Guid userId)
        {
            try
            {
                var userServiceUrl = await _serviceDiscovery.GetServiceUrlAsync("hao-user-api");
                if (string.IsNullOrEmpty(userServiceUrl))
                {
                    return this.ServerErrorResult("用户服务不可用");
                }

                var userInfo = await _httpHelper.GetAsync<object>($"{userServiceUrl}/api/user/{userId}");
                return this.SuccessResult(new 
                {
                    serviceUrl = userServiceUrl,
                    userInfo = userInfo
                }, "成功调用用户服务");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "调用用户服务失败: {UserId}", userId);
                return this.ServerErrorResult($"调用用户服务失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 测试调用商品服务 - 获取商品信息
        /// </summary>
        [HttpGet("test/product/{productId}")]
        [AllowAnonymous]
        public async Task<IActionResult> TestGetProduct(Guid productId)
        {
            try
            {
                var productServiceUrl = await _serviceDiscovery.GetServiceUrlAsync("hao-product-api");
                if (string.IsNullOrEmpty(productServiceUrl))
                {
                    return this.ServerErrorResult("商品服务不可用");
                }

                var productInfo = await _httpHelper.GetAsync<object>($"{productServiceUrl}/api/product/{productId}");
                return this.SuccessResult(new 
                {
                    serviceUrl = productServiceUrl,
                    productInfo = productInfo
                }, "成功调用商品服务");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "调用商品服务失败: {ProductId}", productId);
                return this.ServerErrorResult($"调用商品服务失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 测试服务发现 - 获取所有可用服务
        /// </summary>
        [HttpGet("test/services")]
        [AllowAnonymous]
        public async Task<IActionResult> TestServiceDiscovery()
        {
            try
            {
                var userServices = await _serviceDiscovery.GetHealthyServiceInstancesAsync("hao-user-api");
                var productServices = await _serviceDiscovery.GetHealthyServiceInstancesAsync("hao-product-api");
                var orderServices = await _serviceDiscovery.GetHealthyServiceInstancesAsync("hao-order-api");

                return this.SuccessResult(new 
                {
                    userServices = userServices,
                    productServices = productServices,
                    orderServices = orderServices,
                    timestamp = DateTime.Now
                }, "服务发现测试成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "服务发现测试失败");
                return this.ServerErrorResult($"服务发现测试失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 综合测试 - 模拟创建订单时的服务调用
        /// </summary>
        [HttpPost("test/create-order-simulation")]
        [AllowAnonymous]
        public async Task<IActionResult> TestCreateOrderSimulation([FromBody] TestOrderDto testOrder)
        {
            try
            {
                var results = new List<object>();

                // 1. 调用用户服务验证用户
                try
                {
                    var userServiceUrl = await _serviceDiscovery.GetServiceUrlAsync("hao-user-api");
                    if (!string.IsNullOrEmpty(userServiceUrl))
                    {
                        var userInfo = await _httpHelper.GetAsync<object>($"{userServiceUrl}/api/user/{testOrder.UserId}");
                        results.Add(new { service = "user", status = "success", data = userInfo });
                    }
                    else
                    {
                        results.Add(new { service = "user", status = "unavailable" });
                    }
                }
                catch (Exception ex)
                {
                    results.Add(new { service = "user", status = "error", message = ex.Message });
                }

                // 2. 调用商品服务获取商品信息
                try
                {
                    var productServiceUrl = await _serviceDiscovery.GetServiceUrlAsync("hao-product-api");
                    if (!string.IsNullOrEmpty(productServiceUrl))
                    {
                        var productInfo = await _httpHelper.GetAsync<object>($"{productServiceUrl}/api/product/{testOrder.ProductId}");
                        results.Add(new { service = "product", status = "success", data = productInfo });
                    }
                    else
                    {
                        results.Add(new { service = "product", status = "unavailable" });
                    }
                }
                catch (Exception ex)
                {
                    results.Add(new { service = "product", status = "error", message = ex.Message });
                }

                return this.SuccessResult(new 
                {
                    testOrder = testOrder,
                    serviceCallResults = results,
                    timestamp = DateTime.Now
                }, "订单创建模拟测试完成");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "订单创建模拟测试失败");
                return this.ServerErrorResult($"订单创建模拟测试失败: {ex.Message}");
            }
        }

        #endregion

        /// <summary>
        /// 获取当前用户ID
        /// </summary>
        private Guid GetCurrentUserId()
        {
            var userIdClaim = User.FindFirst("UserId")?.Value;
            if (string.IsNullOrEmpty(userIdClaim) || !Guid.TryParse(userIdClaim, out var userId))
            {
                throw new UnauthorizedAccessException("用户未登录或用户ID无效");
            }
            return userId;
        }
    }

    /// <summary>
    /// 测试订单DTO
    /// </summary>
    public class TestOrderDto
    {
        public Guid UserId { get; set; }
        public Guid ProductId { get; set; }
        public string ProductName { get; set; } = string.Empty;
        public decimal Price { get; set; }
        public int Quantity { get; set; } = 1;
    }
}